<template>
  <view class="container">
    <!-- Header with search bar -->
  <!--  <view class="header">
      <uni-search-bar v-model="searchTerm" @confirm="filterItems" placeholder="搜索调货记录" class="search-bar"></uni-search-bar>
    </view> -->

    <!-- Stock transfer list table -->
    <uni-table :border="true">
      <uni-tr>
        <uni-th align="center">商品编号</uni-th>
        <uni-th align="center">商品名称</uni-th>
        <uni-th align="center">调出门店</uni-th>
        <uni-th align="center">调入门店</uni-th>
        <uni-th align="center">调货数量</uni-th>
		<uni-th align="center">调货规格</uni-th>
        <uni-th align="center">调货时间</uni-th>
      </uni-tr>
      <uni-tr v-for="item in filteredItems" :key="item.id">
        <uni-td align="center">{{ item.product_id }}</uni-td>
        <uni-td align="center">{{ item.product_name }}</uni-td>
        <uni-td align="center">{{ getFromShopName(item.from_shop_id)}}</uni-td>
        <uni-td align="center">{{ getShopById(item.to_shop_id).name }}</uni-td>
        <uni-td align="center">{{ item.quantity }}</uni-td>
		<uni-td align="center">{{ item.spec_name }}</uni-td>

        <uni-td align="center">{{ item.created_at }}</uni-td>
      </uni-tr>
    </uni-table>

    <!-- Popup for editing stock transfer -->
    <uni-popup ref="editPopup" type="center">
      <view class="popup-container">
        <h3>编辑调货信息</h3>
        <view class="form-row">
          <label>选择商品：</label>
          <picker mode="selector" :range="productPickerList" range-key="product_name" v-model="currentItem.product_id" class="input-field">
            <view>{{ getProductById(currentItem.product_id).product_name || '请选择商品' }}</view>
          </picker>
        </view>
        <view class="form-row">
          <label>调出门店：</label>
          <picker mode="selector" :range="shopPickerList" range-key="name" v-model="currentItem.from_shop_id" class="input-field">
            <view>{{ getShopById(currentItem.from_shop_id).name || '请选择调出门店' }}</view>
          </picker>
        </view>
        <view class="form-row">
          <label>调入门店：</label>
          <picker mode="selector" :range="shopPickerList" range-key="name" v-model="currentItem.to_shop_id" class="input-field">
            <view>{{ getShopById(currentItem.to_shop_id).name || '请选择调入门店' }}</view>
          </picker>
        </view>
		
        <view class="form-row">
          <label>调货数量：</label>
          <input v-model="currentItem.quantity" class="input-field" type="number" />
        </view>
        <view class="button-group">
          <uni-button type="primary" size="small" @click="saveTransfer">保存</uni-button>
          <uni-button type="default" size="small" @click="closePopup">取消</uni-button>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
export default {
  data() {
    return {
      searchTerm: '',
      items: [], // 从后端获取的调货记录数据
      filteredItems: [],
      currentItem: { product_id: '', from_shop_id: '', to_shop_id: '', quantity: 0 },
      products: [], // 商品列表
      shops: [], // 门店列表
      productPickerList: [], // 商品选择列表
      shopPickerList: [], // 门店选择列表
      mainAccountId: '',
      userInfo: {}, // 用户信息
    };
  },
  methods: {
    async fetchItems() {
      // 从后端获取调货记录数据
      const res = await this.$myRuquest({
        url: '/index/plugin.users/getStockTransfer',
        method: 'GET',
        data: {
          main_account_id: this.mainAccountId,
        }
      });
      if (res.data.code === 200) {
        this.items = res.data.data;
        this.filteredItems = [...this.items];
      } else {
        uni.showToast({
          title: res.data.message,
          duration: 2000,
          icon: 'none'
        });
      }
    },
    async fetchProducts() {
      // 从后端获取商品列表
      const res = await this.$myRuquest({
        url: '/index/plugin.users/getProducts',
        method: 'GET',
        data: {
          main_account_id: this.mainAccountId,
        }
      });
      if (res.data.code === 200) {
        this.products = res.data.data;
        this.productPickerList = this.products.map(product => ({
          value: product.id,
          product_name: product.product_name
        }));
      } else {
        uni.showToast({
          title: res.data.message,
          duration: 2000,
          icon: 'none'
        });
      }
    },
    async fetchShops() {
      // 从后端获取门店列表
      const res = await this.$myRuquest({
        url: '/index/plugin.users/getStores',
        method: 'GET',
        data: {
          user_id: this.mainAccountId,
        }
      });
      if (res.data.code === 200) {
        this.shops = res.data.data;
        this.shopPickerList = this.shops.map(shop => ({
          value: shop.id,
          name: shop.name
        }));
      } else {
        uni.showToast({
          title: res.data.message,
          duration: 2000,
          icon: 'none'
        });
      }
    },
    filterItems() {
      if (this.searchTerm) {
        this.filteredItems = this.items.filter(item =>
          item.product_name.includes(this.searchTerm) ||
          item.product_id.includes(this.searchTerm)
        );
      } else {
        this.filteredItems = this.items;
      }
    },
	 getFromShopName(id) {
	      if (id <= 0) {
	        return "总库存";
	      } else {
	        return this.getShopById(id).name || "未知门店";
	      }
	    },
    openEditPopup(item) {
      this.currentItem = { ...item };
      this.$refs.editPopup.open();
    },
    closePopup() {
      this.$refs.editPopup.close();
    },
    async saveTransfer() {
      // 保存编辑后的调货记录
      const res = await this.$myRuquest({
        url: '/index/plugin.users/saveStockTransfer',
        method: 'POST',
        data: {
          main_account_id: this.mainAccountId,
          ...this.currentItem
        }
      });
      if (res.data.code === 200) {
        uni.showToast({
          title: '保存成功',
          icon: 'success',
          duration: 2000
        });
        this.fetchItems();
        this.closePopup();
      } else {
        uni.showToast({
          title: res.data.message,
          icon: 'none',
          duration: 2000
        });
      }
    },
    getProductById(id) {
      return this.products.find(product => product.id === id) || {};
    },
    getShopById(id) {
      return this.shops.find(shop => shop.id === id) || {};
    },
    checkLoginStatus() {
      const token = uni.getStorageSync('token');
      if (token) {
        this.userInfo = JSON.parse(uni.getStorageSync('userInfo'));
        this.mainAccountId = this.userInfo.user_id;
      } else {
        this.userInfo = {};
        this.$router.push('/pages/login/login');
      }
    }
  },
  mounted() {
    this.checkLoginStatus();
    this.fetchItems();
    this.fetchProducts();
    this.fetchShops();
  }
};
</script>

<style scoped>
.container {
  padding: 20px;
  background-color: #ecf0f1;
}
.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px;
  background-color: #fff;
  margin-top: 10px;
  margin-bottom: 10px;
  border-radius: 5px;
}
.search-bar {
  flex: 1;
  margin-right: 10px;
}
.uni-table {
  width: 100%;
  border-collapse: collapse;
}
.uni-th, .uni-td {
  padding: 10px;
  border: 1px solid #ddd;
}
.uni-th {
  background-color: #f9f9f9;
}
.popup-container {
  width: 80%;
  max-width: 500px;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}
.form-row {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}
label {
  width: 80px;
  color: #666;
  margin-right: 10px;
}
.input-field {
  flex: 1;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
  outline: none;
}
.button-group {
  display: flex;
  justify-content: space-between;
  margin-top: 20px;
}
.uni-button {
  margin-left: 10px;
}
</style>